package chapter22;

import java.util.ArrayList;
import java.util.List;

/**
 * 基本图算法-强连通分量
 * <p>
 * 任意节点存在u~>v并且同时存在v~>u
 */
public class StronglyConnectedComponents {

    public static void stronglyConnectedComponents(List<Node> V, Node[] G) {
        List<Node> topo = Topo.topoDfs(V, G);
        Node[] GT = reverse(V, G);
        List<Node> VT = new ArrayList<>();
        for (Node v : topo) {
            VT.add(new Node(v.key));
        }
        topo = Topo.topoDfs(VT, GT);
        for (Node u : topo) {
            System.out.println(u);
        }
    }

    public static Node[] reverse(List<Node> V, Node[] G) {
        Node[] GT = new Node[G.length];
        for (int i = 0; i < V.size(); i++) {
            GT[i + 1] = new Node(V.get(i).key);
        }
        for (Node v : V) {
            Node tv = G[v.key];
            Node next = tv.next;
            while (next != null) {
                Node curr = GT[next.key];
                // 加到末端
                while (true) {
                    if (curr.next == null) {
                        curr.next = new Node(tv.key);
                        break;
                    }
                    curr = curr.next;
                }
                next = next.next;
            }
        }
        return GT;
    }
}
